import { AppStore, PagingInfo } from './../../services/appStore';
import { Component, Input, Inject, ElementRef, ChangeDetectorRef, trigger, animate, transition, style, state } from '@angular/core';
@Component({
    selector: 'scrollable-container',
    styleUrls: ['./scrollable-container.scss'],
    template: `
   <div class='scrollable-container'>
      <ng-content></ng-content>
      <div class='fill-gap' style="height:100%;"></div>
    </div>
    `
  })
  export class ScrollableContainer {
  constructor(private element: ElementRef, private appStore: AppStore, private changeDetectorRef: ChangeDetectorRef) {
  }
  lastScrollLeft = 0;
  @Input('class') className;
  @Input()
  ordersArray: Array<any>;
  childrenChanged() {
    this.autoCompleteOrderPanels();
    this.turningPage(0);
  }

  ngAfterViewInit() {
    var textNode = this.element.nativeElement.getElementsByClassName('scrollable-container')[0];
    textNode.classList.add(this.className)
  }
  private autoCompleteOrderPanels() {
    const ele = this.element.nativeElement.firstElementChild;
    const w = ele.clientWidth;
    const fillGapElement = ele.getElementsByClassName('fill-gap')[0]
    const realScrollWidth = ele.scrollWidth - fillGapElement.clientWidth;
    fillGapElement.style.width = ((realScrollWidth % w) ? (w - (realScrollWidth % w)) : (realScrollWidth % w)) + "px";
    //因为order完成之后，ele.scrollLeft会改变，这里吧使用上次的值
    ele.scrollLeft = this.lastScrollLeft;
  }

  private getPagingInfo(): PagingInfo {
    const ele = this.element.nativeElement.firstElementChild;
    const w = ele.clientWidth;
    const scrollLeft = ele.scrollLeft;
    const self = this;
    const ret = {
      orders: this.ordersArray,
      count: { next: 0, previous: 0 }, actions: {
        nextPage() {
          self.turningPage(1);
        },
        previousPage() {
          self.turningPage(-1);
        }
      }
    };
    const orderPanels = Array.from(ele.children);
    orderPanels.pop();
    orderPanels.forEach((v: any, i) => {
      const positionLeft = v.offsetLeft - scrollLeft;
      if (positionLeft < 0) {
        ret.count.previous++;
      } else if (positionLeft >= w) {
        ret.count.next++;
      }
    });
    return ret;
  }

  private turningPage(count: number) {
    //todo 优化
    const ele = this.element.nativeElement.firstElementChild;
    ele.scrollLeft = ele.scrollLeft + ele.clientWidth * count;
    this.lastScrollLeft = ele.scrollLeft;
    this.appStore.gloablStore.actions.changeProduceInfo(this.getPagingInfo())
  }

  }